#include "imagemodel.h"
#include "public/public.h"
#include "qdatetime.h"
#include <QDir>
#include <QFileInfo>
#include <QDebug>
#include <QStandardItemModel>

ImageModel * ImageModel::m_pInstance = NULL;
ImageModel *ImageModel::getInstance()
{
    if(m_pInstance == NULL)
        m_pInstance = new ImageModel();
    return m_pInstance;
}

ImageModel::ImageModel(QObject *parent)
    : QAbstractListModel(parent)
{
    // 加载图片文件并按照时间排序
    QDir imageDir(getPhotoPath());
    QFileInfoList imageFiles = imageDir.entryInfoList(
        QStringList() << "*.jpg" << "*.png",
        QDir::Files | QDir::NoDotAndDotDot,
        QDir::Time
        );

    // 按时间排序
    std::sort(imageFiles.begin(), imageFiles.end(), [](const QFileInfo &a, const QFileInfo &b) {
        return a.birthTime() > b.birthTime();
    });

    beginResetModel();
    for(const QFileInfo &fileInfo : imageFiles) {
        IMAGE img;
        img.strText = fileInfo.fileName();
        img.strPath = fileInfo.absoluteFilePath();
        img.pixFile =  QPixmap(img.strPath );
        img.bSelect = false;  
        m_list.push_back(img); 
    }
    endResetModel();
}

void ImageModel::insertImage(const QString& imagePath)
{
    beginInsertRows(QModelIndex(), 0,0);
    QFileInfo fileInfo(imagePath);
    IMAGE img;
    img.strText = fileInfo.fileName();
    img.strPath = fileInfo.absoluteFilePath();
    img.pixFile =  QPixmap(img.strPath );
    img.bSelect = false;
    m_list.insert(0,img);
    endInsertRows();
} 

void ImageModel::deleteSelectedImages()
{
    for(int i = m_list.size() - 1; i >= 0; i--) {
        if(m_list[i].bSelect) {
            beginRemoveRows(QModelIndex(), i, i);
            // 删除文件
            QFile::remove(m_list[i].strPath);
            m_list.removeAt(i);
            endRemoveRows();
        }
    }
}

void ImageModel::setSelect(int nIndex, bool select)
{
    if(nIndex < m_list.size())
    {
        m_list[nIndex].bSelect = select;
        emit dataChanged(index(nIndex, 0), index(nIndex, 0), {SelectRole});
    }
}


void ImageModel::selectAll(bool select)
{
    for(int i = 0; i < m_list.size(); i++) {
        m_list[i].bSelect = select;
    }
    emit dataChanged(index(0, 0), index(m_list.size()-1, 0), {SelectRole});
}

int ImageModel::rowCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent);
    return m_list.count();
}

QVariant ImageModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid() || index.row() >= m_list.size()) {
        return QVariant();
    }
    switch(role)
    {
    case Qt::DecorationRole:
        return m_list[index.row()].pixFile;
    case PathRole:
        return m_list[index.row()].strPath;
    case TextRole:
        return m_list[index.row()].strText;
    case SelectRole:
        return m_list[index.row()].bSelect;
    }
    return QVariant();
}
